<template>
  <div class="search">
    <el-container>
      <el-header class="search-header">
        <div class="search-container">
          <el-input
            id="search-input"
            name="search"
            v-model="searchQuery"
            placeholder="搜索视频、电影、电视剧..."
            size="large"
            clearable
            @keyup.enter="handleSearch"
            @input="handleInputChange"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch" :loading="searching">搜索</el-button>
            </template>
          </el-input>
          
          <!-- 搜索建议 -->
          <div v-if="showSuggestions && searchSuggestions.length > 0" class="search-suggestions">
            <div
              v-for="suggestion in searchSuggestions"
              :key="suggestion"
              class="suggestion-item"
              @click="selectSuggestion(suggestion)"
            >
              <el-icon><Search /></el-icon>
              <span>{{ suggestion }}</span>
            </div>
          </div>
        </div>
      </el-header>

      <el-main>
        <!-- 搜索结果 -->
        <div v-if="searchResults.length > 0" class="search-results">
          <div class="results-header">
            <h2>搜索结果 ({{ totalResults }})</h2>
            <div class="sort-options">
              <el-select v-model="sortBy" @change="handleSearch" placeholder="排序方式">
                <el-option label="相关度" value="relevance"></el-option>
                <el-option label="最热" value="views"></el-option>
                <el-option label="最新" value="created_at"></el-option>
                <el-option label="最多点赞" value="likes"></el-option>
              </el-select>
            </div>
          </div>
          
          <div class="results-grid">
            <div
              v-for="result in searchResults"
              :key="result.id"
              class="result-card"
              data-aos="fade-up"
              @click="goToDetail(result.id)"
            >
              <div class="result-thumbnail">
                <img :src="result.thumbnail" :alt="result.title" />
                <span class="duration">{{ result.duration }}</span>
                <div class="video-overlay">
                  <el-icon class="play-icon"><CaretRight /></el-icon>
                </div>
              </div>
              <div class="result-info">
                <h3 v-html="highlightText(result.title)"></h3>
                <p>{{ result.description }}</p>
                <div class="result-meta">
                  <span class="views">
                    <el-icon><View /></el-icon>{{ formatViews(result.views) }} 次播放
                  </span>
                  <span class="likes">
                    <el-icon><Star /></el-icon>{{ result.likes }} 点赞
                  </span>
                  <span class="category">{{ result.category?.name || '未分类' }}</span>
                  <span class="date">{{ formatDate(result.created_at) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="totalPages > 1" class="pagination-container">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :total="totalResults"
              layout="prev, pager, next"
              @current-change="handlePageChange"
            />
          </div>
        </div>

        <!-- 搜索建议和推荐 -->
        <div v-else-if="showSuggestions" class="suggestions">
          <div class="suggestion-sections">
            <!-- 热门搜索 -->
            <div class="suggestion-section">
              <h2>热门搜索</h2>
              <div class="hot-tags">
                <el-tag
                  v-for="tag in hotTags"
                  :key="tag"
                  class="tag-item"
                  @click="searchTag(tag)"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <!-- 搜索历史 -->
            <div v-if="searchHistory.length > 0" class="suggestion-section">
              <h2>搜索历史</h2>
              <div class="history-tags">
                <el-tag
                  v-for="(item, index) in searchHistory"
                  :key="index"
                  class="tag-item history-tag"
                  @click="searchTag(item)"
                  closable
                  @close="removeFromHistory(index)"
                >
                  {{ item }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 为您推荐 -->
          <div class="recommended-section">
            <h2>为您推荐</h2>
            <div class="recommended-grid">
              <div
                v-for="video in recommendedVideos"
                :key="video.id"
                class="video-card"
                data-aos="fade-up"
                @click="goToDetail(video.id)"
              >
                <div class="video-thumbnail">
                  <img :src="video.thumbnail" :alt="video.title" />
                  <span class="duration">{{ video.duration }}</span>
                  <div class="video-overlay">
                    <el-icon class="play-icon"><CaretRight /></el-icon>
                  </div>
                </div>
                <div class="video-info">
                  <h3>{{ video.title }}</h3>
                  <p>{{ formatViews(video.views) }} 次播放</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 无搜索结果 -->
        <div v-else-if="hasSearched && searchResults.length === 0" class="no-results">
          <el-empty description="没有找到相关视频">
            <template #image>
              <el-icon size="100" color="#999"><Search /></el-icon>
            </template>
            <el-button type="primary" @click="clearSearch">重新搜索</el-button>
          </el-empty>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElContainer, ElHeader, ElMain, ElInput, ElButton, ElIcon, ElTag, ElEmpty, ElSelect, ElOption, ElPagination } from 'element-plus'
import { Search, View, Star, CaretRight } from '@element-plus/icons-vue'
import AOS from 'aos'
import 'aos/dist/aos.css'
import api from '@/utils/axios'

const router = useRouter()
const searchQuery = ref('')
const searchResults = ref([])
const searching = ref(false)
const hasSearched = ref(false)
const sortBy = ref('relevance')
const currentPage = ref(1)
const pageSize = ref(12)
const totalResults = ref(0)
const searchSuggestions = ref([])
const searchHistory = ref([])

const showSuggestions = computed(() => searchQuery.value === '' && !hasSearched.value)
const totalPages = computed(() => Math.ceil(totalResults.value / pageSize.value))

const hotTags = ref(['动作片', '喜剧片', '科幻片', '爱情片', '恐怖片', '复仇者联盟', '速度与激情', '功夫熊猫', '星际穿越', '盗梦空间'])

const recommendedVideos = ref([])

// 加载推荐视频
const loadRecommendedVideos = async () => {
  try {
    const response = await api.get('/videos/recommended')
    if (response.success) {
      recommendedVideos.value = response.data.slice(0, 8)
    }
  } catch (error) {
    console.error('加载推荐视频失败:', error)
  }
}

// 加载搜索历史
const loadSearchHistory = () => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
}

// 保存搜索历史
const saveSearchHistory = (query) => {
  if (!query.trim()) return
  
  // 移除重复项
  const index = searchHistory.value.indexOf(query)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
  }
  
  // 添加到开头
  searchHistory.value.unshift(query)
  
  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
  
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 从历史记录中移除
const removeFromHistory = (index) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 处理输入变化
const handleInputChange = () => {
  if (searchQuery.value.length > 0) {
    // 这里可以添加搜索建议的API调用
    searchSuggestions.value = hotTags.value.filter(tag => 
      tag.toLowerCase().includes(searchQuery.value.toLowerCase())
    ).slice(0, 5)
  } else {
    searchSuggestions.value = []
  }
}

// 选择搜索建议
const selectSuggestion = (suggestion) => {
  searchQuery.value = suggestion
  searchSuggestions.value = []
  handleSearch()
}

// 执行搜索
const handleSearch = async () => {
  if (!searchQuery.value.trim()) return
  
  try {
    searching.value = true
    hasSearched.value = true
    
    const params = {
      search: searchQuery.value,
      page: currentPage.value,
      per_page: pageSize.value
    }
    
    // 根据排序方式设置参数
    if (sortBy.value !== 'relevance') {
      params.sort_by = sortBy.value
      params.order = 'desc'
    }
    
    const response = await api.get('/videos', { params })
    if (response.success) {
      searchResults.value = response.data.data.map(video => ({
        ...video,
        category: video.category?.name || '未分类'
      }))
      totalResults.value = response.data.total
      
      // 保存搜索历史
      saveSearchHistory(searchQuery.value)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    totalResults.value = 0
  } finally {
    searching.value = false
  }
}

// 搜索标签
const searchTag = (tag) => {
  searchQuery.value = tag
  searchSuggestions.value = []
  handleSearch()
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
  hasSearched.value = false
  currentPage.value = 1
  searchSuggestions.value = []
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  handleSearch()
}

// 高亮搜索关键词
const highlightText = (text) => {
  if (!searchQuery.value) return text
  const regex = new RegExp(`(${searchQuery.value})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

// 格式化播放量
const formatViews = (views) => {
  if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  }
  return views.toString()
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

onMounted(() => {
  AOS.init({
    duration: 1000,
    easing: 'ease-in-out'
  })
  loadRecommendedVideos()
  loadSearchHistory()
})
</script>

<style scoped>
.search {
  width: 100vw;
  max-width: none;
  min-height: 100vh;
  background: #0a0a0a;
  color: #fff;
  margin: 0;
  padding: 0;
}

.search-header {
  padding: 20px;
  background: #1a1a1a;
  border-bottom: 1px solid #333;
}

.search-container {
  position: relative;
  max-width: 800px;
  margin: 0 auto;
}

.search-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #1a1a1a;
  border: 1px solid #333;
  border-top: none;
  border-radius: 0 0 8px 8px;
  z-index: 1000;
  max-height: 300px;
  overflow-y: auto;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  gap: 8px;
}

.suggestion-item:hover {
  background: #2a2a2a;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #333;
}

.results-header h2 {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
}

.results-grid,
.recommended-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-top: 20px;
}

.result-card,
.video-card {
  background: #1a1a1a;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #333;
}

.result-card:hover,
.video-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 24px rgba(255,255,255,0.1);
  border-color: #409eff;
}

.result-thumbnail,
.video-thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
  overflow: hidden;
}

.result-thumbnail img,
.video-thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.result-card:hover .result-thumbnail img,
.video-card:hover .video-thumbnail img {
  transform: scale(1.05);
}

.duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0,0,0,0.8);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.result-card:hover .video-overlay,
.video-card:hover .video-overlay {
  opacity: 1;
}

.play-icon {
  font-size: 48px;
  color: #fff;
  background: rgba(64, 158, 255, 0.8);
  border-radius: 50%;
  padding: 12px;
}

.result-info,
.video-info {
  padding: 20px;
}

h3 {
  color: #fff;
  margin-bottom: 8px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

h3 :deep(mark) {
  background: #409eff;
  color: #fff;
  padding: 2px 4px;
  border-radius: 3px;
}

.result-info p {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.result-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.result-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.result-meta .views {
  color: #409eff;
}

.result-meta .likes {
  color: #f56c6c;
}

.result-meta .category {
  color: #67c23a;
}

.result-meta .date {
  color: #909399;
}

.suggestions {
  padding: 20px;
}

.suggestion-sections {
  margin-bottom: 40px;
}

.suggestion-section {
  margin-bottom: 30px;
}

.suggestion-section h2 {
  color: #fff;
  font-size: 20px;
  margin-bottom: 16px;
}

.hot-tags,
.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-item {
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.history-tag {
  background: #2a2a2a;
  border-color: #444;
}

.recommended-section h2 {
  color: #fff;
  font-size: 20px;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #333;
}

.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 响应式设计 - 优化版本 */
@media (min-width: 1920px) {
  .search-header {
    padding: 40px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
  
  .suggestions {
    padding: 30px;
  }
}

@media (min-width: 1600px) {
  .search-header {
    padding: 35px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  }
  
  .suggestions {
    padding: 25px;
  }
}

@media (min-width: 1400px) {
  .search-header {
    padding: 30px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
  
  .suggestions {
    padding: 20px;
  }
}

@media (min-width: 1200px) {
  .search-header {
    padding: 25px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
  
  .suggestions {
    padding: 18px;
  }
}

@media (min-width: 992px) {
  .search-header {
    padding: 20px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  }
  
  .suggestions {
    padding: 16px;
  }
}

@media (min-width: 768px) {
  .search-header {
    padding: 18px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
  
  .suggestions {
    padding: 15px;
  }
}

@media (min-width: 576px) {
  .search-header {
    padding: 16px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
  
  .suggestions {
    padding: 14px;
  }
}

@media (max-width: 575px) {
  .search-header {
    padding: 15px;
  }
  
  .results-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .result-info,
  .video-info {
    padding: 16px;
  }
  
  .suggestions {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .results-grid,
  .recommended-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
  
  .hot-tags,
  .history-tags {
    gap: 8px;
  }
  
  .tag-item {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .history-tag {
    padding: 4px 8px;
    font-size: 11px;
  }
}
</style>

